﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using DBService;
using YArchitech.Controls;
using YArchitech.Controls.HeaderGridView;
using YArchitech.Revit.MEP.Opening;

namespace HYRMEOpening
{
	public partial class DlgOpeningDetect : System.Windows.Forms.Form
	{
		public static DlgOpeningDetect GetInstance(List<DbOpeningBase> ol, UIApplication app, bool server, bool linkModel, string fileName)
		{
			if (DlgOpeningDetect.dov == null || DlgOpeningDetect.dov.IsDisposed)
			{
				DlgOpeningDetect.dov = new DlgOpeningDetect(ol, app, server, linkModel, fileName);
			}
			return DlgOpeningDetect.dov;
		}

		public Request Request
		{
			get
			{
				return this.m_request;
			}
			private set
			{
				this.m_request = value;
			}
		}

		private void MakeRequest(RequestId request)
		{
			this.Request.Make(request);
		}

		public DlgOpeningDetect(List<DbOpeningBase> ol, UIApplication app, bool server, bool linkModel, string fileName)
		{
			this.isServer = server;
			this.isLinkModel = linkModel;
			this.UiDoc = app.ActiveUIDocument;
			this.UiApp = app;
			this.mFileName = fileName;
			this.OpiningList = new BindingList<DbOpeningBase>(ol);
			this.InitializeComponent();
			this.Request = new Request();
			if (server)
			{
				this.rbByFile.Checked = false;
				this.rbByServer.Checked = true;
				this.tbFileName.Visible = false;
				return;
			}
			this.rbByFile.Checked = true;
			this.rbByServer.Checked = false;
			this.tbFileName.Visible = true;
			this.tbFileName.Text = fileName;
		}

		private void TurnToView3D(UIDocument uiDoc)
		{
			if (!(uiDoc.ActiveView is View3D))
			{
				View3D view3D = null;
				Transaction transaction = new Transaction(uiDoc.Document, "DelView");
				try
				{
					transaction.Start();
					FilteredElementCollector filteredElementCollector = new FilteredElementCollector(uiDoc.Document);
					filteredElementCollector.OfClass(typeof(View3D));
					foreach (Element element in filteredElementCollector.ToElements())
					{
						if (element.Name == "盈建科开洞浏览")
						{
							view3D = (element as View3D);
							break;
						}
					}
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
				}
				if (view3D == null)
				{
					Transaction transaction2 = new Transaction(uiDoc.Document, "cv");
					try
					{
						transaction2.Start();
						FilteredElementCollector filteredElementCollector2 = new FilteredElementCollector(uiDoc.Document);
						filteredElementCollector2.WhereElementIsNotElementType();
						filteredElementCollector2.ToElements();
                        ViewFamilyType viewFamilyType = new FilteredElementCollector(uiDoc.Document).OfClass(typeof(ViewFamilyType)).Cast<ViewFamilyType>().FirstOrDefault((ViewFamilyType x) => 102 == (int)x.ViewFamily);
						view3D = View3D.CreateIsometric(uiDoc.Document, viewFamilyType.Id);
						view3D.Name = "盈建科开洞浏览";
						view3D.DetailLevel = (ViewDetailLevel)3;
                        view3D.DisplayStyle = (DisplayStyle)6;
						new List<ElementId>();
						transaction2.Commit();
					}
					catch
					{
						transaction2.RollBack();
						base.Close();
					}
				}
				uiDoc.ActiveView = view3D;
			}
		}

		private void DlgOpeningDetect_Load(object sender, EventArgs e)
		{
			this.TurnToView3D(this.UiDoc);
			this.dgvOpeningList.DataSource = this.OpiningList;
			DataGridViewComboBoxColumn dataGridViewComboBoxColumn = new DataGridViewComboBoxColumn();
			dataGridViewComboBoxColumn.DisplayStyle = DataGridViewComboBoxDisplayStyle.ComboBox;
			dataGridViewComboBoxColumn.DisplayIndex = 7;
			dataGridViewComboBoxColumn.DataSource = ConfigDataOperate.GetDrivePipeTypeName();
			dataGridViewComboBoxColumn.Name = "DrivePipeTypeName";
			dataGridViewComboBoxColumn.HeaderText = "套管类型";
			this.dgvOpeningList.Columns.Add(dataGridViewComboBoxColumn);
			dataGridViewComboBoxColumn.Visible = false;
			foreach (object obj in ((IEnumerable)this.dgvOpeningList.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				((DataGridViewComboBoxCell)dataGridViewRow.Cells["DrivePipeTypeName"]).Value = this.OpiningList[dataGridViewRow.Index].DrivePipeTypeName;
				int num = dataGridViewRow.Index + 1;
				dataGridViewRow.Cells["colNumber"].Value = num.ToString();
			}
			foreach (object obj2 in this.dgvOpeningList.Columns)
			{
				DataGridViewColumn dataGridViewColumn = (DataGridViewColumn)obj2;
				dataGridViewColumn.DefaultCellStyle.BackColor = System.Drawing.Color.DarkGray;
				dataGridViewColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
				string name = dataGridViewColumn.Name;
				if (name.Equals("IsCurrentProject") || name.Equals("IsOpened") || name.Equals("OpeningStatusString"))
				{
					dataGridViewColumn.Visible = false;
				}
			}
			this.MakeRequest(RequestId.AddTag);
		}

		private void btnDel_Click(object sender, EventArgs e)
		{
			foreach (object obj in this.dgvOpeningList.SelectedRows)
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				if (dataGridViewRow.Cells["CutTypeString"].Value.ToString() == "其他")
				{
					this.DelOpening = this.OpiningList[dataGridViewRow.Index];
					this.MakeRequest(RequestId.DelTag);
					this.OpiningList.RemoveAt(dataGridViewRow.Index);
					IEnumerator enumerator2 = ((IEnumerable)this.dgvOpeningList.Rows).GetEnumerator();
					{
						while (enumerator2.MoveNext())
						{
							object obj2 = enumerator2.Current;
							DataGridViewRow dataGridViewRow2 = (DataGridViewRow)obj2;
							int num = dataGridViewRow2.Index + 1;
							dataGridViewRow2.Cells["colNumber"].Value = num.ToString();
						}
						continue;
					}
				}
				MessageBox.Show("只能删除自定义洞口。");
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			if (new OfferDataConfigForm().ShowDialog() == DialogResult.OK && YJKMessageBox.Show("是否更新提资数据?", MessageBoxButtons.YesNo) == DialogResult.Yes)
			{
				ConfigDataOperate.OfferConfigData offerConfigData = new ConfigDataOperate.OfferConfigData(ConfigDataOperate.InitConfigDataFile());
				foreach (DbOpeningBase dbOpeningBase in this.OpiningList)
				{
                    DBService.SectionType sectionType = dbOpeningBase.SectionParameter.SectionType;
                    if (sectionType != DBService.SectionType.Rect)
					{
						if (sectionType == DBService.SectionType.Arc)
						{
							dbOpeningBase.BoxParameter.Parameter1 = (dbOpeningBase.BoxParameter.Parameter2 = (dbOpeningBase.BoxParameter.Parameter3 = (dbOpeningBase.BoxParameter.Parameter4 = offerConfigData.CircelOpeningDist2Pipe)));
						}
					}
					else
					{
						dbOpeningBase.BoxParameter.Parameter1 = (dbOpeningBase.BoxParameter.Parameter2 = (dbOpeningBase.BoxParameter.Parameter3 = (dbOpeningBase.BoxParameter.Parameter4 = offerConfigData.RectOpeningDist2Pipe)));
					}
				}
				this.dgvOpeningList.Refresh();
			}
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			this.MakeRequest(RequestId.ClearTag);
			base.Close();
		}

		private void btnEdit_Click(object sender, EventArgs e)
		{
			if (this.dgvOpeningList.SelectedRows.Count > 0)
			{
				int index = this.dgvOpeningList.SelectedRows[0].Index;
				BindingList<DbOpeningBase> bindingList = (BindingList<DbOpeningBase>)this.dgvOpeningList.DataSource;
				this.OpeningToChange = bindingList[index];
				new DlgEdit(this.OpeningToChange).ShowDialog(this);
				this.dgvOpeningList.Update();
				this.dgvOpeningList.Refresh();
				this.MakeRequest(RequestId.ChangeOpeningStyle);
			}
		}

		private void btnSubmit_Click(object sender, EventArgs e)
		{
			BindingList<DbOpeningBase> bindingList = (BindingList<DbOpeningBase>)this.dgvOpeningList.DataSource;
			try
			{
				if (!this.isServer)
				{
					new FileInfo(this.mFileName).Delete();
					YArchitech.Revit.MEP.Opening.XmlUtils.CreateDataFile(this.mFileName, this.UiDoc.Document);
				}
				else
				{
					DbOpeningBase.ClearFromDbByProject(DbProject.GetProjectByCurrentDoc(this.UiDoc.Document));
				}
				foreach (DbOpeningBase dbOpeningBase in bindingList)
				{
					if (this.isServer)
					{
						dbOpeningBase.AddToDb(BimServerDB.Default);
					}
					else
					{
						dbOpeningBase.WirteToXML(this.mFileName);
					}
				}
				foreach (DbOpeningBase dbOpeningBase2 in this.m_lstInvalidOpenings)
				{
					dbOpeningBase2.IsValid = false;
					dbOpeningBase2.WirteToXML(this.mFileName);
				}
				if (this.isServer)
				{
					DbProject projectByCurrentDoc = DbProject.GetProjectByCurrentDoc(this.UiDoc.Document);
					if (projectByCurrentDoc == null)
					{
						goto IL_172;
					}
					using (List<DbUser>.Enumerator enumerator3 = projectByCurrentDoc.GetAllArchEngineer().GetEnumerator())
					{
						while (enumerator3.MoveNext())
						{
							DbUser dbUser = enumerator3.Current;
							DbUser.System.SendMessage(dbUser.Name, "项目" + projectByCurrentDoc.Name + "开动数据已更新。");
						}
						goto IL_172;
					}
				}
				YArchitech.Revit.MEP.Opening.XmlUtils.SetAutoCasing(this.mFileName, YArchitech.Revit.MEP.Opening.XmlUtils.AutoCreateCasing());
				YArchitech.Revit.MEP.Opening.XmlUtils.SetCasingType(this.mFileName, YArchitech.Revit.MEP.Opening.XmlUtils.GetCastingType());
				IL_172:
				MessageBox.Show("已成功提交。");
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void rbByFile_CheckedChanged(object sender, EventArgs e)
		{
		}

		private void rbByServer_CheckedChanged(object sender, EventArgs e)
		{
		}

		private void tbFileName_TextChanged(object sender, EventArgs e)
		{
		}

		private void dgvOpeningList_MouseClick(object sender, MouseEventArgs e)
		{
		}

		private void dgvOpeningList_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			this.CheckOpeningElement();
		}

		private void DlgOpeningDetect_FormClosing(object sender, FormClosingEventArgs e)
		{
			this.MakeRequest(RequestId.ClearTag);
		}

		private void button1_Click(object sender, EventArgs e)
		{
			double mergeOpeningMaxDist = new ConfigDataOperate.OfferConfigData(ConfigDataOperate.InitConfigDataFile()).MergeOpeningMaxDist;
			List<DbOpeningBase> list = new List<DbOpeningBase>();
			Dictionary<int, List<DbOpeningBase>> dictionary = new Dictionary<int, List<DbOpeningBase>>();
			foreach (DbOpeningBase dbOpeningBase in this.OpiningList.ToList<DbOpeningBase>())
			{
				if (dbOpeningBase is DbBeamToBeOpened)
				{
					list.Add(dbOpeningBase);
				}
				else if (!dictionary.ContainsKey(dbOpeningBase.HostId))
				{
					List<DbOpeningBase> list2 = new List<DbOpeningBase>();
					list2.Add(dbOpeningBase);
					dictionary.Add(dbOpeningBase.HostId, list2);
				}
				else
				{
					dictionary[dbOpeningBase.HostId].Add(dbOpeningBase);
				}
			}
			List<DbOpeningBase> list3 = new List<DbOpeningBase>();
			foreach (List<DbOpeningBase> list4 in dictionary.Values)
			{
				if (list4.Count == 1)
				{
					list3.Add(list4[0]);
				}
				else
				{
					list3.AddRange(DbOpeningBase.Combine(list4, this.UiApp, mergeOpeningMaxDist, mergeOpeningMaxDist, true));
				}
			}
			list3.AddRange(list);
			CmdOpeningToDb.UpdateOpeningAxisXYData(list3, this.UiDoc.Document);
			this.OpiningList = new BindingList<DbOpeningBase>(list3);
			this.dgvOpeningList.DataSource = this.OpiningList;
			this.MakeRequest(RequestId.AddTag);
			foreach (object obj in ((IEnumerable)this.dgvOpeningList.Rows))
			{
				DataGridViewRow dataGridViewRow = (DataGridViewRow)obj;
				int num = dataGridViewRow.Index + 1;
				dataGridViewRow.Cells["colNumber"].Value = num.ToString();
			}
			YJKMessageBox.Show("合并成功！");
		}

		private void btnExport_Click(object sender, EventArgs e)
		{
			this.dgvOpeningList.ExportExcel();
		}

		private void dgvOpeningList_CellContentClick(object sender, DataGridViewCellEventArgs e)
		{
		}

		private void btnCheck_Click(object sender, EventArgs e)
		{
			this.CheckOpeningElement();
		}

		private void CheckOpeningElement()
		{
			if (this.dgvOpeningList.SelectedRows.Count > 0)
			{
				int index = this.dgvOpeningList.SelectedRows[0].Index;
				DbOpeningBase dbOpeningBase = ((BindingList<DbOpeningBase>)this.dgvOpeningList.DataSource)[index];
				if (dbOpeningBase is DbWallToBeOpened)
				{
					DbWallToBeOpened dbWallToBeOpened = (DbWallToBeOpened)dbOpeningBase;
					new ElementId(dbWallToBeOpened.HostId);
					Element element = DbOpeningBase.FindTag(dbOpeningBase, this.UiDoc.Document);
					if (element != null)
					{
						List<Element> list = new List<Element>();
						list.Add(element);
						RevitVersionFuncs.SetSelection(this.UiDoc.Selection, list);
						UIView uiview = null;
						foreach (UIView uiview2 in this.UiDoc.GetOpenUIViews())
						{
							if (uiview2.ViewId.Equals(this.UiDoc.ActiveView.Id))
							{
								uiview = uiview2;
								break;
							}
						}
						XYZ xyz = dbWallToBeOpened.Location;
						XYZ xyz2 = dbWallToBeOpened.Location;
						xyz += new XYZ(-3.0, -3.0, 0.0);
						xyz2 += new XYZ(3.0, 3.0, 0.0);
						uiview.ZoomAndCenterRectangle(xyz, xyz2);
						return;
					}
				}
				else if (dbOpeningBase is DbFloorToBeOpened)
				{
					DbFloorToBeOpened dbFloorToBeOpened = (DbFloorToBeOpened)dbOpeningBase;
					ElementId id = new ElementId(dbFloorToBeOpened.HostId);
					RevitVersionFuncs.GetElement(this.UiDoc.Document, id);
					Element element2 = DbOpeningBase.FindTag(dbOpeningBase, this.UiDoc.Document);
					if (element2 != null)
					{
						List<Element> list2 = new List<Element>();
						list2.Add(element2);
						RevitVersionFuncs.SetSelection(this.UiDoc.Selection, list2);
						UIView uiview3 = null;
						foreach (UIView uiview4 in this.UiDoc.GetOpenUIViews())
						{
							if (uiview4.ViewId.Equals(this.UiDoc.ActiveView.Id))
							{
								uiview3 = uiview4;
								break;
							}
						}
						XYZ xyz3 = dbFloorToBeOpened.Location;
						XYZ xyz4 = dbFloorToBeOpened.Location;
						xyz3 += new XYZ(-3.0, -3.0, 0.0);
						xyz4 += new XYZ(3.0, 3.0, 0.0);
						uiview3.ZoomAndCenterRectangle(xyz3, xyz4);
					}
				}
			}
		}

		private void dgvOpeningList_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
		{
			if (this.dgvOpeningList.CurrentCell.OwningColumn.Name == "DrivePipeTypeName")
			{
				((System.Windows.Forms.ComboBox)e.Control).SelectedIndexChanged -= this.ComboBox_SelectedIndexChanged;
				((System.Windows.Forms.ComboBox)e.Control).SelectedIndexChanged += this.ComboBox_SelectedIndexChanged;
			}
		}

		private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
		{
			System.Windows.Forms.ComboBox comboBox = sender as System.Windows.Forms.ComboBox;
			if (comboBox == null || comboBox.SelectedItem == null)
			{
				return;
			}
			int rowIndex = this.dgvOpeningList.CurrentCell.RowIndex;
			string name = this.dgvOpeningList.CurrentCell.OwningColumn.Name;
			string drivePipeTypeName = comboBox.SelectedItem.ToString();
			if (name == "DrivePipeTypeName")
			{
				this.OpiningList[rowIndex].DrivePipeTypeName = drivePipeTypeName;
			}
		}

		private void DlgOpeningDetect_KeyDown(object sender, KeyEventArgs e)
		{
			try
			{
				Keys keyCode = e.KeyCode;
				if (keyCode == Keys.Escape)
				{
					base.Close();
				}
			}
			catch
			{
			}
		}

		public UIDocument UiDoc;

		public UIApplication UiApp;

		private bool isServer;

		private string mFileName;

		private bool isLinkModel;

		public BindingList<DbOpeningBase> OpiningList = new BindingList<DbOpeningBase>();

		public List<DbOpeningBase> m_lstInvalidOpenings = new List<DbOpeningBase>();

		private static DlgOpeningDetect dov;

		private Request m_request;

		public DbOpeningBase DelOpening;

		public DbOpeningBase NewTag;

		public DbOpeningBase OpeningToChange;
	}
}
